// React核心库导入
import React, { useEffect, useCallback } from 'react';
// Ant Design组件库导入
import { 
  Table,      // 表格组件
  Button,     // 按钮组件
  Space,      // 间距组件
  Tag,        // 标签组件
  Card,       // 卡片组件
  Input,      // 输入框组件
  Select,     // 选择器组件
  Badge,      // 徽章组件
  Tooltip,    // 工具提示组件
  message,    // 消息提示组件
  Popconfirm  // 确认对话框组件
} from 'antd';
// Ant Design表格类型导入
import type { ColumnsType } from 'antd/es/table';
// Ant Design图标库导入
import { 
  PlusOutlined,        // 加号图标
  EditOutlined,        // 编辑图标
  DeleteOutlined,      // 删除图标
  ReloadOutlined,      // 刷新图标
  SearchOutlined,      // 搜索图标
  SettingOutlined,     // 设置图标
  EyeOutlined,         // 查看图标
  CheckCircleOutlined, // 成功图标
  CloseCircleOutlined, // 失败图标
  PlayCircleOutlined,  // 播放图标
  PauseCircleOutlined  // 暂停图标
} from '@ant-design/icons';
// React Router路由组件导入
import { Link } from 'react-router-dom';
// 状态管理Hook导入
import { useAgent, useAgentLoading, useAgentError, useAgentFilters, useAgents } from '@contexts/AgentContext';
// 服务层导入
import { AgentStatus, AgentType } from '@services/agentService';
// 性能优化Hook导入
import { useDebounce, useThrottle } from '@hooks/usePerformance';
import { useLocalStorageCache } from '@hooks/useCache';
import { withPerformance } from '@hooks/usePerformance';

// 解构组件
const { Search } = Input;
const { Option } = Select;

/**
 * 智能体列表组件 - 智能体管理主页面
 * 
 * 功能特性：
 * - 智能体数据列表展示和分页
 * - 多条件搜索和过滤功能
 * - 智能体状态管理操作
 * - 批量操作支持
 * - 实时状态监控
 * - 响应式设计支持
 * 
 * @author CKY Agent Platform Team
 * @version 2.0.0
 * @lastModified 2024-01-20
 */
const AgentList: React.FC = () => {
  // 使用状态管理Hook
  const { state, actions } = useAgent();
  const loading = useAgentLoading();
  const error = useAgentError();
  const { filters, setFilters, resetFilters } = useAgentFilters();
  const agents = useAgents();

  // 定义缓存过滤器接口
  interface CachedFilters {
    filter: string;
    status: AgentStatus | undefined;
    agentType: AgentType | undefined;
    isActive: boolean | undefined;
  }

  // 使用本地存储缓存用户的过滤设置
  const [cachedFilters, setCachedFilters] = useLocalStorageCache<CachedFilters>(
    'agent-list-filters',
    { filter: '', status: undefined, agentType: undefined, isActive: undefined },
    { ttl: 24 * 60 * 60 * 1000 } // 24小时
  );

  // 恢复缓存的过滤设置
  useEffect(() => {
    if (cachedFilters.filter) {
      setFilters(cachedFilters);
    }
  }, [cachedFilters]);

  // 状态显示映射
  const statusMap = {
    [AgentStatus.NotConfigured]: { text: '未配置', color: 'default', icon: <SettingOutlined /> },
    [AgentStatus.Configured]: { text: '已配置', color: 'processing', icon: <CheckCircleOutlined /> },
    [AgentStatus.Running]: { text: '运行中', color: 'success', icon: <PlayCircleOutlined /> },
    [AgentStatus.Stopped]: { text: '已停止', color: 'warning', icon: <PauseCircleOutlined /> },
    [AgentStatus.Error]: { text: '错误', color: 'error', icon: <CloseCircleOutlined /> }
  };

  // 类型显示映射
  const typeMap = {
    [AgentType.Chat]: '聊天助手',
    [AgentType.Assistant]: '智能助手',
    [AgentType.Analyst]: '数据分析',
    [AgentType.Creative]: '创意生成',
    [AgentType.Custom]: '自定义'
  };

  // 使用防抖优化搜索功能
  const debouncedSearch = useDebounce((value: string) => {
    setFilters({ filter: value, skipCount: 0 });
    // 缓存搜索设置
    setCachedFilters({
      filter: value,
      status: filters.status,
      agentType: filters.agentType,
      isActive: filters.isActive
    });
  }, 300);

  // 使用节流优化过滤操作
  const throttledStatusFilter = useThrottle((value: AgentStatus | undefined) => {
    setFilters({ status: value, skipCount: 0 });
    setCachedFilters({
      filter: filters.filter || '',
      status: value,
      agentType: filters.agentType,
      isActive: filters.isActive
    });
  }, 200);

  const throttledTypeFilter = useThrottle((value: AgentType | undefined) => {
    setFilters({ agentType: value, skipCount: 0 });
    setCachedFilters({
      filter: filters.filter || '',
      status: filters.status,
      agentType: value,
      isActive: filters.isActive
    });
  }, 200);

  const throttledActiveFilter = useThrottle((value: boolean | undefined) => {
    setFilters({ isActive: value, skipCount: 0 });
    setCachedFilters({
      filter: filters.filter || '',
      status: filters.status,
      agentType: filters.agentType,
      isActive: value
    });
  }, 200);

  // 处理搜索
  const handleSearch = (value: string) => {
    debouncedSearch(value);
  };

  // 处理状态过滤
  const handleStatusFilter = (value: AgentStatus | undefined) => {
    throttledStatusFilter(value);
  };

  // 处理类型过滤
  const handleTypeFilter = (value: AgentType | undefined) => {
    throttledTypeFilter(value);
  };

  // 处理激活状态过滤
  const handleActiveFilter = (value: boolean | undefined) => {
    throttledActiveFilter(value);
  };

  // 处理分页变化
  const handleTableChange = (pagination: any) => {
    setFilters({
      skipCount: (pagination.current - 1) * pagination.pageSize,
      maxResultCount: pagination.pageSize
    });
  };

  // 删除智能体
  const handleDelete = async (id: string) => {
    try {
      await actions.deleteAgent(id);
      message.success('删除成功');
    } catch (error) {
      message.error('删除失败');
    }
  };

  // 更新智能体状态
  const handleStatusChange = async (id: string, status: AgentStatus) => {
    try {
      await actions.updateAgentStatus(id, status);
      message.success('状态更新成功');
    } catch (error) {
      message.error('状态更新失败');
    }
  };

  // 激活/停用智能体
  const handleToggleActive = async (id: string, isActive: boolean) => {
    try {
      if (isActive) {
        await actions.activateAgent(id);
        message.success('激活成功');
      } else {
        await actions.deactivateAgent(id);
        message.success('停用成功');
      }
    } catch (error) {
      message.error(isActive ? '激活失败' : '停用失败');
    }
  };

  // 刷新数据
  const handleRefresh = () => {
    actions.fetchAgents();
  };

  // 重置过滤器
  const handleResetFilters = useCallback(() => {
    resetFilters();
    setCachedFilters({ filter: '', status: undefined, agentType: undefined, isActive: undefined });
  }, [resetFilters, setCachedFilters]);

  // 表格列定义
  const columns: ColumnsType<any> = [
    {
      title: '名称',
      dataIndex: 'name',
      key: 'name',
      render: (text: string, record: any) => (
        <Link to={`/agents/${record.id}`} style={{ fontWeight: 'bold' }}>
          {text}
        </Link>
      ),
      sorter: true,
      width: 200
    },
    {
      title: '描述',
      dataIndex: 'description',
      key: 'description',
      ellipsis: true,
      width: 250
    },
    {
      title: '类型',
      dataIndex: 'agentType',
      key: 'agentType',
      render: (type: AgentType) => (
        <Tag color="blue">
          {typeMap[type] || type}
        </Tag>
      ),
      filters: Object.entries(typeMap).map(([value, label]) => ({
        text: label,
        value: parseInt(value)
      })),
      width: 120
    },
    {
      title: '状态',
      dataIndex: 'status',
      key: 'status',
      render: (status: AgentStatus) => {
        const statusInfo = statusMap[status] || { text: '未知', color: 'default' };
        return (
          <Badge
            status={statusInfo.color as any}
            text={statusInfo.text}
            style={{ display: 'flex', alignItems: 'center' }}
          />
        );
      },
      filters: Object.entries(statusMap).map(([value, { text }]) => ({
        text: text,
        value: parseInt(value)
      })),
      width: 120
    },
    {
      title: '模型配置',
      dataIndex: 'modelConfigName',
      key: 'modelConfigName',
      render: (text: string) => text || '-',
      width: 150
    },
    {
      title: '使用统计',
      key: 'stats',
      render: (_, record: any) => (
        <Space direction="vertical" size="small">
          <div>使用: {record.usageCount || 0}</div>
          <div>成功: {record.successCount || 0}</div>
          <div>失败: {record.failureCount || 0}</div>
        </Space>
      ),
      width: 120
    },
    {
      title: '激活状态',
      dataIndex: 'isActive',
      key: 'isActive',
      render: (isActive: boolean, record: any) => (
        <Tag color={isActive ? 'success' : 'default'}>
          {isActive ? '激活' : '停用'}
        </Tag>
      ),
      filters: [
        { text: '激活', value: true },
        { text: '停用', value: false }
      ],
      width: 100
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      key: 'createdAt',
      render: (text: string) => new Date(text).toLocaleString(),
      sorter: true,
      width: 160
    },
    {
      title: '操作',
      key: 'actions',
      render: (_, record: any) => (
        <Space size="small">
          <Tooltip title="查看详情">
            <Link to={`/agents/${record.id}`}>
              <Button icon={<EyeOutlined />} size="small" />
            </Link>
          </Tooltip>
          
          <Tooltip title="编辑">
            <Link to={`/agents/${record.id}/edit`}>
              <Button icon={<EditOutlined />} size="small" />
            </Link>
          </Tooltip>

          <Tooltip title={record.isActive ? '停用' : '激活'}>
            <Button
              icon={record.isActive ? <PauseCircleOutlined /> : <PlayCircleOutlined />}
              size="small"
              onClick={() => handleToggleActive(record.id, !record.isActive)}
            />
          </Tooltip>

          {record.status === AgentStatus.Running && (
            <Tooltip title="停止">
              <Button
                icon={<PauseCircleOutlined />}
                size="small"
                onClick={() => handleStatusChange(record.id, AgentStatus.Stopped)}
              />
            </Tooltip>
          )}

          <Popconfirm
            title="确定要删除这个智能体吗？"
            onConfirm={() => handleDelete(record.id)}
            okText="确定"
            cancelText="取消"
          >
            <Tooltip title="删除">
              <Button icon={<DeleteOutlined />} size="small" danger />
            </Tooltip>
          </Popconfirm>
        </Space>
      ),
      fixed: 'right',
      width: 180
    }
  ];

  // 计算分页配置
  const paginationConfig = {
    current: Math.floor((filters.skipCount || 0) / (filters.maxResultCount || 10)) + 1,
    pageSize: filters.maxResultCount || 10,
    total: state.totalCount,
    showSizeChanger: true,
    showQuickJumper: true,
    showTotal: (total: number, range: [number, number]) => 
      `第 ${range[0]}-${range[1]} 条，共 ${total} 条`,
    pageSizeOptions: ['10', '20', '50', '100']
  };

  // 错误处理
  useEffect(() => {
    if (error) {
      message.error(error);
    }
  }, [error]);

  return (
    <div style={{ padding: '24px' }}>
      <Card>
        {/* 页面标题和操作栏 */}
        <div style={{ marginBottom: '24px' }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: '16px' }}>
            <h1 style={{ margin: 0, fontSize: '24px', fontWeight: 'bold' }}>
              智能体管理
            </h1>
            <Space>
              <Button icon={<ReloadOutlined />} onClick={handleRefresh} loading={loading}>
                刷新
              </Button>
              <Link to="/agents/create">
                <Button type="primary" icon={<PlusOutlined />}>
                  创建智能体
                </Button>
              </Link>
            </Space>
          </div>
          
          {/* 搜索和过滤区域 */}
          <div style={{ display: 'flex', gap: '12px', flexWrap: 'wrap' }}>
            <Search
              placeholder="搜索智能体名称或描述"
              style={{ width: 300 }}
              onSearch={handleSearch}
              enterButton={<SearchOutlined />}
              allowClear
            />
            
            <Select
              placeholder="状态过滤"
              style={{ width: 120 }}
              allowClear
              onChange={handleStatusFilter}
            >
              {Object.entries(statusMap).map(([value, { text }]) => (
                <Option key={value} value={parseInt(value)}>
                  {text}
                </Option>
              ))}
            </Select>

            <Select
              placeholder="类型过滤"
              style={{ width: 120 }}
              allowClear
              onChange={handleTypeFilter}
            >
              {Object.entries(typeMap).map(([value, label]) => (
                <Option key={value} value={parseInt(value)}>
                  {label}
                </Option>
              ))}
            </Select>

            <Select
              placeholder="激活状态"
              style={{ width: 120 }}
              allowClear
              onChange={handleActiveFilter}
            >
              <Option value={true}>激活</Option>
              <Option value={false}>停用</Option>
            </Select>

            <Button onClick={handleResetFilters}>
              重置过滤
            </Button>
          </div>
        </div>

        {/* 数据统计信息 */}
        <div style={{ marginBottom: '16px', padding: '12px', backgroundColor: '#f5f5f5', borderRadius: '6px' }}>
          <Space size="large">
            <span>总智能体数: <strong>{state.totalCount}</strong></span>
            <span>激活: <strong>{agents.filter(a => a.isActive).length}</strong></span>
            <span>运行中: <strong>{agents.filter(a => a.status === AgentStatus.Running).length}</strong></span>
            <span>错误: <strong>{agents.filter(a => a.status === AgentStatus.Error).length}</strong></span>
          </Space>
        </div>

        {/* 数据表格 */}
        <Table
          columns={columns}
          dataSource={agents}
          rowKey="id"
          loading={loading}
          pagination={paginationConfig}
          onChange={handleTableChange}
          scroll={{ x: 1200 }}
          bordered
          size="middle"
        />
      </Card>
    </div>
  );
};

// 使用性能优化高阶组件包装
export default withPerformance(AgentList, { memoize: true });